In C#, struct (short for structure) is a
value type used to store related data under a single unit. It's similar to a class, but with some key differences in behavior and use cases.
What is a Structure?
A structure is a user-defined type that groups different variables under one name. Structs are best used for small data containers that don’t require inheritance or complex behaviors.
struct StructName
{
// Fields
public int field1;
public string field2;
// Constructor
public StructName(int f1, string f2)
{
field1 = f1;
field2 = f2;
}
// Methods
public void Display()
{
Console.WriteLine($"Field1: {field1}, Field2: {field2}");
}
}
Example: Defining and Using a Struct
using System;
struct Employee
{
public int ID;
public string EmployeeName;
public Employee(int id, string name)
{
ID = id;
EmployeeName = name;
}
public void Display()
{
Console.WriteLine($"ID: {ID}, Name: {EmployeeName}");
}
}
class Program
{
static void Main()
{
Employee emp1 = new Employee(101, "Alice");
emp1.Display();
}
}
Output:
ID: 101, Name: Alice
Struct vs Class
| Feature | struct |
class |
|---|---|---|
| Type | Value type | Reference type |
| Memory allocation | Stack | Heap |
| Inheritance | Not supported | Supported |
| Performance | Faster for small data | Suitable for complex models |
| Null assignment | Not allowed (unless nullable) | Allowed |
| Default constructor | Not allowed (you define it) | Provided automatically |
When to Use Struct?
Use a struct when:
- You’re representing simple objects (like a point, color, coordinate).
- You want value semantics (copying data instead of references).
- You don’t need inheritance or polymorphism.
Additional Notes
- Structs can implement interfaces, but cannot inherit from another struct or class.
- You can use
Nullable<T>orT?with structs if you want to allownullvalues. - Structs are copied by value, not by reference. So changes made to one copy don't affect the original.
Mini Quiz
struct Point {
public int X, Y;
}
Point p1 = new Point();
p1.X = 5;
Point p2 = p1; // Now it assign
p2.X = 10;
Console.WriteLine(p1.X);
Summery
| Concept | Explanation |
|---|---|
struct keyword |
Defines a structure |
| Value type | Stored on the stack |
| No inheritance | Cannot inherit from classes or other structs |
| Lightweight | Best for small, immutable data |
| Copy behavior | Passed and assigned by value |
Read More
Structure types - C# reference
Leave Comment